#!/bin/sh


#$1 config.zip file
CONFIG_ZIP_FILE=$1

#$2 0: rewrite tozed_param	1: append write tozed_param
CONFIG_UPDATE_WAY=$2

UPDATE_CONFIG_STATUS_SUCCESS=/tmp/.update_config_success
UPDATE_CONFIG_STATUS_FAIL=/tmp/.update_config_fail
UPDATE_CONFIG_STATUS_ING=/tmp/.update_config_ing

CONFIG_WORK_STATION=/tmp/update_station/config/

FACTORY_CONFIG_FILE=/etc/tozed_param
FACTORY_FLAG=/etc/.flag_factory_config

zip_pwd=tz18c6

config_go_exit()
{
        rm ${UPDATE_CONFIG_STATUS_ING} -f
        if [ "$1" = "success" ]; then
                rm ${UPDATE_CONFIG_STATUS_FAIL} -f
                touch ${UPDATE_CONFIG_STATUS_SUCCESS}
                echo "success"
        else
                rm ${UPDATE_CONFIG_STATUS_SUCCESS} -f
                touch ${UPDATE_CONFIG_STATUS_FAIL}
		if [ "$2" != "" ]; then
			echo "$2" > ${UPDATE_CONFIG_STATUS_FAIL}
                        echo "failed: $2"
                else
                        echo "failed: none"
		fi
        fi
        exit
}

touch ${UPDATE_CONFIG_STATUS_ING}

if [ "${CONFIG_ZIP_FILE}" = "" -o ! -f ${CONFIG_ZIP_FILE} ]; then
	config_go_exit "fail" "the config zip file is not exist"
fi


mkdir -p ${CONFIG_WORK_STATION}
rm -rf ${CONFIG_WORK_STATION}/*

#unzip
unzip -P ${zip_pwd} ${CONFIG_ZIP_FILE} -d ${CONFIG_WORK_STATION}  1>/dev/null 2>/dev/null

cd ${CONFIG_WORK_STATION}
if [ ! -f md5sum.txt ]; then
        config_go_exit "fail" "the config md5.txt not exist"
fi

config_md5_value_in_file=`cat md5sum.txt | awk '{print $1}'`

config_file=`ls | grep .conf`
config_md5_value_by_cal=`md5sum ${config_file} | awk '{print $1}'`

if [ "${config_md5_value_in_file}" != "${config_md5_value_by_cal}" ]; then
        config_go_exit "fail" "md5sum is error!"
fi


##start update config

#logo
if [ -d ${CONFIG_WORK_STATION}/LOGO ]; then
        logo_nums=`ls ${CONFIG_WORK_STATION}/LOGO/*.gif | wc -l`
        if [ "${logo_nums}" = "1" ]; then
                cp ${CONFIG_WORK_STATION}/LOGO/*.gif /tz_www/images/customer.gif
        fi
fi

#get the config file
tozed_tool -a ${CONFIG_WORK_STATION}/${config_file} 1>/dev/null 2>/dev/null

toolret=`cat /tmp/.tozed_tool_ret | awk '{print $1}'`
if [ "${toolret}" != "success" ]; then
	config_go_exit "fail" "tozed_tool decript conf fail"
fi

if [ ! -f /tmp/config_param_file ]; then
	config_go_exit "fail" " the /tmp/config_param_file is not exist"
fi

# CONFIG_UPDATE_WAY = "0" rewrite the tozed_param and set the reset factory flag.
if [ "${CONFIG_UPDATE_WAY}" = "0" ]; then
	cp /tmp/config_param_file ${FACTORY_CONFIG_FILE}
	rm /etc/config/wireless
	touch ${FACTORY_FLAG}
fi


config_go_exit "success"



